import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';
import 'dart:async';

class PlatformJumpGamePage extends StatefulWidget {
  const PlatformJumpGamePage({super.key});

  @override
  State<PlatformJumpGamePage> createState() => _PlatformJumpGamePageState();
}

class _PlatformJumpGamePageState extends State<PlatformJumpGamePage>
    with TickerProviderStateMixin {
  // 游戏状态
  bool isGameRunning = true;
  int score = 0;
  
  // 屏幕尺寸
  double screenWidth = 0;
  double screenHeight = 0;
  
  // 玩家属性
  double playerX = 100;
  double playerY = 300;
  double playerWidth = 30;
  double playerHeight = 40;
  double playerVelocityX = 0;
  double playerVelocityY = 0;
  bool isOnGround = false;
  bool isFacingRight = true;
  
  // 物理常量
  final double gravity = 0.8;
  final double jumpForce = -15;
  final double moveSpeed = 5;
  final double friction = 0.8;
  
  // 平台列表
  List<Platform> platforms = [];
  
  // 虚拟摇杆
  Offset joystickCenter = const Offset(0, 0);
  Offset joystickPosition = const Offset(0, 0);
  bool isJoystickActive = false;
  
  // 动画控制器
  late AnimationController gameLoopController;
  
  // 随机数生成器
  final Random random = Random();
  
  @override
  void initState() {
    super.initState();
    
    // 设置横屏模式
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    
    // 隐藏状态栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
    
    // 初始化游戏循环
    gameLoopController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 16), // 约60FPS
    );
    
    gameLoopController.addListener(() {
      if (isGameRunning) {
        updateGame();
      }
    });
    
    gameLoopController.repeat();
    
    // 延迟初始化，等待布局完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initializeGame();
    });
  }
  
  @override
  void dispose() {
    // 恢复竖屏模式
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    
    // 恢复状态栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, 
      overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    
    gameLoopController.dispose();
    super.dispose();
  }
  
  void initializeGame() {
    setState(() {
      screenWidth = MediaQuery.of(context).size.width;
      screenHeight = MediaQuery.of(context).size.height;
      
      // 调整摇杆位置到左下角
      joystickCenter = Offset(80, screenHeight - 80);
      
      // 生成初始平台
      generatePlatforms();
    });
  }
  
  void generatePlatforms() {
    platforms.clear();
    
    // 添加地面
    platforms.add(Platform(
      x: 0,
      y: screenHeight - 20,
      width: screenWidth,
      height: 20,
      color: Colors.green,
    ));
    
    // 生成随机平台 - 横屏模式下生成更多平台
    for (int i = 0; i < 12; i++) {
      double x = random.nextDouble() * (screenWidth - 100);
      double y = 100 + random.nextDouble() * (screenHeight - 200);
      double width = 60 + random.nextDouble() * 120; // 横屏模式下平台可以更宽
      
      platforms.add(Platform(
        x: x,
        y: y,
        width: width,
        height: 15,
        color: Colors.blue,
      ));
    }
  }
  
  void updateGame() {
    if (!mounted) return;
    
    setState(() {
      // 更新玩家位置
      playerX += playerVelocityX;
      playerY += playerVelocityY;
      
      // 应用重力
      playerVelocityY += gravity;
      
      // 应用摩擦力
      playerVelocityX *= friction;
      
      // 检查平台碰撞
      checkPlatformCollisions();
      
      // 边界检查
      if (playerX < 0) {
        playerX = 0;
        playerVelocityX = 0;
      }
      if (playerX + playerWidth > screenWidth) {
        playerX = screenWidth - playerWidth;
        playerVelocityX = 0;
      }
      
      // 检查是否掉出屏幕
      if (playerY > screenHeight) {
        resetPlayer();
      }
      
      // 更新分数
      score++;
    });
  }
  
  void checkPlatformCollisions() {
    isOnGround = false;
    
    for (Platform platform in platforms) {
      if (playerX < platform.x + platform.width &&
          playerX + playerWidth > platform.x &&
          playerY + playerHeight > platform.y &&
          playerY + playerHeight < platform.y + platform.height + 10 &&
          playerVelocityY > 0) {
        
        // 着陆在平台上
        playerY = platform.y - playerHeight;
        playerVelocityY = 0;
        isOnGround = true;
        break;
      }
    }
  }
  
  void resetPlayer() {
    playerX = 100;
    playerY = 300;
    playerVelocityX = 0;
    playerVelocityY = 0;
  }
  
  void handleJoystickMove(Offset position) {
    setState(() {
      joystickPosition = position;
      
      // 计算摇杆偏移
      Offset offset = position - joystickCenter;
      double distance = offset.distance;
      double maxDistance = 40;
      
      if (distance > maxDistance) {
        offset = offset / distance * maxDistance;
      }
      
      // 根据摇杆位置设置移动速度
      if (distance > 10) {
        playerVelocityX = (offset.dx / maxDistance) * moveSpeed;
        isFacingRight = playerVelocityX > 0;
      } else {
        playerVelocityX = 0;
      }
    });
  }
  
  void handleJump() {
    if (isOnGround) {
      setState(() {
        playerVelocityY = jumpForce;
        isOnGround = false;
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue[100],
      body: Stack(
        children: [
          // 游戏区域
          CustomPaint(
            size: Size.infinite,
            painter: GamePainter(
              playerX: playerX,
              playerY: playerY,
              playerWidth: playerWidth,
              playerHeight: playerHeight,
              platforms: platforms,
              isFacingRight: isFacingRight,
            ),
          ),
          
          // 分数显示 - 调整到右上角
          Positioned(
            top: 30,
            right: 30,
            child: Container(
              padding: const EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(15),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black26,
                    blurRadius: 5,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Text(
                '分数: $score',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          
          // 跳跃按钮 - 调整到右下角
          Positioned(
            bottom: 80,
            right: 80,
            child: GestureDetector(
              onTapDown: (_) => handleJump(),
              child: Container(
                width: 70,
                height: 70,
                decoration: BoxDecoration(
                  color: Colors.orange,
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black26,
                      blurRadius: 8,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.keyboard_arrow_up,
                  color: Colors.white,
                  size: 35,
                ),
              ),
            ),
          ),
          
          // 虚拟摇杆 - 调整到左下角
          Positioned(
            bottom: 80,
            left: 80,
            child: GestureDetector(
              onPanStart: (details) {
                setState(() {
                  isJoystickActive = true;
                  joystickPosition = details.localPosition;
                });
              },
              onPanUpdate: (details) {
                handleJoystickMove(details.localPosition);
              },
              onPanEnd: (details) {
                setState(() {
                  isJoystickActive = false;
                  joystickPosition = joystickCenter;
                  playerVelocityX = 0;
                });
              },
              child: Container(
                width: 140,
                height: 140,
                decoration: BoxDecoration(
                  color: Colors.black26,
                  shape: BoxShape.circle,
                ),
                child: Stack(
                  children: [
                    // 摇杆背景
                    Center(
                      child: Container(
                        width: 100,
                        height: 100,
                        decoration: BoxDecoration(
                          color: Colors.white54,
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                    // 摇杆手柄
                    Positioned(
                      left: joystickPosition.dx - 20,
                      top: joystickPosition.dy - 20,
                      child: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: isJoystickActive ? Colors.blue : Colors.grey,
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black26,
                              blurRadius: 5,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          
          // 游戏说明 - 调整到左上角
          Positioned(
            top: 30,
            left: 30,
            child: Container(
              padding: const EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(15),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black26,
                    blurRadius: 5,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '横屏游戏控制',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 5),
                  Text(
                    '左下角: 摇杆控制移动\n右下角: 跳跃按钮',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 返回按钮
          Positioned(
            top: 30,
            left: 200,
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.red.withOpacity(0.8),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(
                  Icons.arrow_back,
                  color: Colors.white,
                  size: 24,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class Platform {
  final double x;
  final double y;
  final double width;
  final double height;
  final Color color;
  
  Platform({
    required this.x,
    required this.y,
    required this.width,
    required this.height,
    required this.color,
  });
}

class GamePainter extends CustomPainter {
  final double playerX;
  final double playerY;
  final double playerWidth;
  final double playerHeight;
  final List<Platform> platforms;
  final bool isFacingRight;
  
  GamePainter({
    required this.playerX,
    required this.playerY,
    required this.playerWidth,
    required this.playerHeight,
    required this.platforms,
    required this.isFacingRight,
  });
  
  @override
  void paint(Canvas canvas, Size size) {
    // 绘制平台
    for (Platform platform in platforms) {
      final paint = Paint()
        ..color = platform.color
        ..style = PaintingStyle.fill;
      
      canvas.drawRect(
        Rect.fromLTWH(platform.x, platform.y, platform.width, platform.height),
        paint,
      );
    }
    
    // 绘制玩家
    final playerPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;
    
    canvas.drawRect(
      Rect.fromLTWH(playerX, playerY, playerWidth, playerHeight),
      playerPaint,
    );
    
    // 绘制玩家眼睛
    final eyePaint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;
    
    if (isFacingRight) {
      canvas.drawCircle(
        Offset(playerX + playerWidth - 8, playerY + 10),
        3,
        eyePaint,
      );
    } else {
      canvas.drawCircle(
        Offset(playerX + 8, playerY + 10),
        3,
        eyePaint,
      );
    }
  }
  
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
} 